package org.alino.core.shiro.filter;

import org.alino.core.Consts;
import org.alino.core.shiro.model.UserBase;
import org.alino.core.shiro.service.IUserService;
import org.alino.core.shiro.token.TokenManager;
import org.alino.core.utils.JsonUtils;
import org.alino.core.utils.LoggerUtils;
import org.alino.core.utils.RequestUtils;
import org.alino.core.utils.ReturnUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Desc 判断登录
 * @Author by Brant
 * @Date 2017/1/13
 */
public class LoginFilter extends AccessControlFilter {
    @Autowired
    IUserService userService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        UserBase token = TokenManager.getToken();
        if(null != token){
            UserBase dbUser = userService.findUserByUserId(token.getId());
            if(Consts.USER_STATUS_NOT_LOCKED.equals(dbUser.getStatus()) || Consts.USER_STATUS_NOT_DELETED.equals(dbUser.getStatus())){
                TokenManager.logout();
                return Boolean.FALSE;
            }
        }
        if(null != token || isLoginRequest(request, response)){// && isEnabled()
            return Boolean.TRUE;
        }
        if (RequestUtils.isAjaxRequest((HttpServletRequest) request)) {// ajax请求
            LoggerUtils.debug(getClass(), "当前用户没有登录");
            JsonUtils.write((HttpServletResponse) response, ReturnUtils.NOTLOGIN);
        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {
        //保存Request和Response 到登录后的链接
        saveRequestAndRedirectToLogin(request, response);
        return Boolean.FALSE ;
    }
}
